package com.apex.flink.transform.functions;

import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.table.functions.FunctionContext;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringLengthUdf extends ScalarFunction {
    @Override
    public void open(FunctionContext context) throws Exception {
        super.open(context);
    }

    public long eval(String a) {
        return a == null ? 0 : a.length();
    }

    public long eval(String b, String c) {
        return eval(b) + eval(c);
    }


    public long eval(String a,String b,String c){
        StringBuilder builder = new StringBuilder();
        if (isNumeric(a)){
            builder.append(a);
        }

        if (isNumeric(b)){
            builder.append(b);
        }

        if (isNumeric(c)){
            builder.append(c);
        }
        return new BigDecimal(builder.toString()).longValue();
    }

    @Override
    public void close() {
    }

    /**
     *
     * @param s
     * @return
     */
    public boolean isNumeric(String s){
        Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
        Matcher isNum = pattern.matcher(s);
       return isNum.matches();
    }
}
